const {
	commentModel
} = require('../models/comment.model')

console.log(commentModel)

module.exports = class Comment {

	//添加评论
	static async addComment(ctx) {
		console.log('ctx.request.body--', ctx.request.body)

		let {
			body,
			articleId,
			authorId
		} = ctx.request.body

		if (!(body || articleId || authorId)) {
			return ctx.fail({
				msg: '缺少必填项'
			})
		}
		const newComment = new commentModel({
			body,
			author: authorId,
			article: articleId
		})
		await newComment.save()
		return ctx.success({
			msg: '评论成功'
		})
	}

	//删除评论
	static async deleteComment(ctx) {
		let {
			id
		} = ctx.request.body
		const res = await commentModel.remove({
			_id: id
		})
		if (res.ok == 1) {
			return ctx.success({
				msg: '删除成功'
			})
		} else {
			return ctx.fail({
				msg: '删除失败'
			})
		}
	}
	//所有评论
	static async allComment(ctx) {
		let page = 1;
		let size = 10
		let query = {}
		let comments = []

		if (ctx.request.query.size != undefined) {
			size = ctx.request.query.size;
		}

		if (ctx.request.query.page != undefined) {
			page = ctx.request.query.page;
		}

		if (ctx.request.query.userId != undefined) {
			let userId = ctx.request.query.userId;
			query.author = {
				$in: [userId]
			} //查询参数：按照发表人id查询
		}
		if (ctx.request.query.articleId != undefined) {
			let articleId = ctx.request.query.articleId;
			query.article = {
				$in: [articleId]
			} //查询参数：按照文章id查询
		}

		console.log('query--', query)
		//分页
		comments = await commentModel.find(query)
			.skip(Number(page - 1) * Number(size))
			.limit(Number(size))
			.sort({
				creatAt: -1
			})
		// comments = comments.map(comment => comment.getAuthorInfo(comment.author))
		let res = [];
		for(let i=0;i<comments.length;i++){
			let comment = comments[i]
			let item = {
				body:comment.body,
				article:comment.article,
				author:comment.author,
				authorInfo:await comment.getAuthorInfo(comment.author)
			}
			res.push(item)
		}

		return ctx.success({
			msg: '获取成功',
			data: {
				comments:res,
				total: comments.length
			}
		})
	}
}
